package com.zrkizzy.seckill.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.javafaker.Faker;
import com.zrkizzy.seckill.entity.User;
import com.zrkizzy.seckill.vo.common.Result;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

/**
 * 用户工具类
 *
 * @author zhangrongkang
 * @since 2023/4/2
 */
public class UserUtil {

    /**
     * 文件路径
     */
    private static final String FILE_PATH = "这里写你希望生成文件的路径（路径最后需要加上 '/'）";
    /**
     * 文件名称
     */
    private static final String FILE_NAME = "config.txt";

    /**
     * 生成指定数量的用户
     *
     * @param count 用户数量
     */
    private static void createUser(int count) throws Exception {
        // 随机运营商
        Random random = new Random();
        // 实例化Faker对象， 地点选择中国
        Faker faker = Faker.instance(Locale.CHINA);
        // 用于生成用户的集合
        List<User> users = new ArrayList<>();
        // 生成对应数量的用户
        for (int i = 0; i < count; i++) {
            User user = User.builder()
                    .id(PhoneNumberUtil.createPhoneNumberLong(random.nextInt(3)))
                    .nickname(faker.name().nameWithMiddle())
                    .slat("1a2b3c4d")
                    .password(Md5Util.inputPassToDbPass("123456", "1a2b3c4d"))
                    .registerDate(LocalDateTime.now())
                    .build();
            // 将当前的用于添加到用户集合中
            users.add(user);
        }
        System.out.println("开始创建用户...");
        // 1. 获取数据库连接
        Connection connection = DbUtil.getConnection();
        // 2. 编写SQL语句
        String sql = "INSERT INTO tb_user(id, nickname, slat, password, register_date) VALUES(?, ?, ?, ?, ?)";
        // 3. 预编译SQL语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 遍历生成的用户集合
        for (User user : users) {
            // 给预编译中的变量进行赋值
            preparedStatement.setLong(1, user.getId());
            preparedStatement.setString(2, user.getNickname());
            preparedStatement.setString(3, user.getSlat());
            preparedStatement.setString(4, user.getPassword());
            preparedStatement.setString(5, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(user.getRegisterDate()));
            preparedStatement.addBatch();
        }
        // 4. 批量执行SQL语句
        preparedStatement.executeBatch();
        // 5. 关闭对应SQL资源
        DbUtil.close(preparedStatement);

        System.out.println("开始执行用户登录逻辑...");

        // 定义登录路径
        String loginUrl = "http://localhost:8080/login/doLogin";
        File file = new File(FILE_PATH + FILE_NAME);
        // 如果文件已经存在就将文件删除
        if (file.exists()) {
            file.delete();
        }
        RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
        accessFile.seek(0);
        for (User user : users) {
            // 定义URL连接对象
            URL url = new URL(loginUrl);
            // 打开连接并将URL连接对象转为Http连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            // 设置Http连接参数对象
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            // 获取到当前Http连接的输出流
            OutputStream outputStream = urlConnection.getOutputStream();
            // 定义入参
            String params = "mobile=" + user.getId() + "&password=" + Md5Util.inputPassToFromPass("123456");
            // 写入到输出流中
            outputStream.write(params.getBytes());
            outputStream.flush();
            // 获取输入流
            InputStream inputStream = urlConnection.getInputStream();
            // 封装输出流
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            // 定义每一次读取的大小
            byte[] buffer = new byte[1024];
            int length = 0;
            // 写入
            while ((length = inputStream.read(buffer)) >= 0) {
                // 将当前行的内容写如刀输出流数组中
                arrayOutputStream.write(buffer, 0, length);
            }
            inputStream.close();
            arrayOutputStream.close();
            // 获取到输出的响应结果
            String response = new String(arrayOutputStream.toByteArray());

            ObjectMapper objectMapper = new ObjectMapper();
            // 获取到用户携带的票据
            Result result = objectMapper.readValue(response, Result.class);
            String userTicket = (String) result.getObj();
            System.out.println("用户票据：" + userTicket + ", 对应用户：" + user.getNickname());
            // 定义要在txt文件中输出的每一行数据
            String row = user.getId() + "," + userTicket;
            accessFile.write(row.getBytes());
            // 换行
            accessFile.write("\r\n".getBytes());
            System.out.println("写入文件的用户：" + user.getNickname() + "：" + user.getId());
        }
        // 关闭流
        accessFile.close();
        System.out.println("流程结束...");
    }

    public static void main(String[] args) throws Exception {
        createUser(20);
    }
}
